package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Dialog;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.sax.StartElementListener;
import android.text.Html;
import android.view.Window;

import com.exercise.AndroidCamera.R;

/*
기능 : 슬라이드리스트
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class SlideListAdapter extends BaseAdapter {

	Intent i;
	String userID;
	Double meter;
	
	private Context c;
	private LayoutInflater flater;
	public static String mode="";
	Typeface tf;
	Activity activity;

	public SlideListAdapter(Context c, int layout, String userID, Double meter, Activity activity) {
		// TODO Auto-generated constructor stub
		this.c = c;
		flater = (LayoutInflater)c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
		this.userID = userID;
		tf = Typeface.createFromAsset(c.getAssets(), "fonts/whitechok.ttf");
		this.meter = meter;
		this.activity = activity;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return 1;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	/* 모든 버튼 객체화*/
	public static class ViewHolder{
		Button modify_info;
		Button my_news;
		Button add_new_friends;
		Button management_friends;
		Button management_group;
		Button member_leave;
		Button setting;
		Button logout;
		Button friend_news;
		Button all_news;
		Button group_news;
		Button five_meter;
		Button one_kilometer;
		Button three_kilometer;
		Button five_kilometer;
		
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int pos = position;
		ViewHolder holder = null;
		Log.i("map","call slide getview");
	
		if(convertView == null)
		{
			holder = new ViewHolder();
			convertView = flater.inflate(R.layout.side_list_layout, parent,false);
			holder.modify_info = (Button)convertView.findViewById(R.id.modify_info_btn);
			holder.modify_info.setTypeface(tf);
			holder.my_news = (Button)convertView.findViewById(R.id.my_news);
			holder.my_news.setTypeface(tf);
			holder.add_new_friends = (Button)convertView.findViewById(R.id.add_new_friend);
			holder.add_new_friends.setTypeface(tf);
			holder.management_friends = (Button)convertView.findViewById(R.id.management_friend_btn);
			holder.management_friends.setTypeface(tf);
			holder.management_group = (Button)convertView.findViewById(R.id.management_group_btn);
			holder.management_group.setTypeface(tf);
			holder.member_leave = (Button)convertView.findViewById(R.id.member_leave_btn);
			holder.member_leave.setTypeface(tf);
			holder.logout = (Button)convertView.findViewById(R.id.logout);
			holder.logout.setTypeface(tf);
			holder.friend_news = (Button)convertView.findViewById(R.id.friend_news);
			holder.friend_news.setTypeface(tf);
			holder.all_news = (Button)convertView.findViewById(R.id.all_news);
			holder.all_news.setTypeface(tf);
			holder.group_news = (Button)convertView.findViewById(R.id.group_news);
			holder.group_news.setTypeface(tf);
			holder.five_meter = (Button)convertView.findViewById(R.id.fivemeterButton);
			holder.one_kilometer = (Button)convertView.findViewById(R.id.onekilometerButton);
			holder.three_kilometer = (Button)convertView.findViewById(R.id.threekilometerButton);
			holder.five_kilometer = (Button)convertView.findViewById(R.id.fivekilometerButton);

			convertView.setTag(holder);
		}
		else
		{
			holder = (ViewHolder)convertView.getTag();
		}
		/*현재 반경의 따라 직관적으로 보여주게 하기 위해 값을 다르게 줌*/
		if(meter==0.5)
		{	
			holder.five_meter.setBackgroundResource(R.drawable.onedotfiveclick);
		}else if(meter==1.0){
			holder.one_kilometer.setBackgroundResource(R.drawable.oneclick);
		}else if(meter==3.0){
			holder.three_kilometer.setBackgroundResource(R.drawable.threeclick);
		}else if(meter==5.0){
			holder.five_kilometer.setBackgroundResource(R.drawable.fiveclick);
		}
		/*현재 모드를 직관적이로 뵤여주게 하기 위해 값을 다르게 줌*/
		if(mode.equals("all"))
		{	
			holder.all_news.setBackgroundResource(R.drawable.click);
		}else if(mode.equals("friend")){
			holder.friend_news.setBackgroundResource(R.drawable.click);
		}else if(mode.equals("group")){
			holder.group_news.setBackgroundResource(R.drawable.click);
		}else{
			holder.all_news.setBackgroundResource(R.drawable.click);
		}
		
		/*내 정보 수정*/
		holder.modify_info.setOnClickListener(new View.OnClickListener() {
	         
	         @Override
	         public void onClick(View v) {
	            // TODO Auto-generated method stub
	            int btnMyPost = 0;
	            Log.d("my_news", "my_news");
	            Intent mIntent = new Intent(c, ModifyInfoActivity.class);
	             Activity a = (Activity)c;
	              mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	              mIntent.putExtra("userID", userID);
	              mIntent.putExtra("locationID", "0");
	              mIntent.putExtra("groupID", "1");
	              a.startActivity(mIntent);
	         }
	      });
		/*나의 소식*/
		holder.my_news.setOnClickListener(new View.OnClickListener() {
	         
	         @Override
	         public void onClick(View v) {
	            // TODO Auto-generated method stub
	            int btnMyPost = 0;
	            Log.d("my_news", "my_news");
	            Intent mIntent = new Intent(c, PostListActivity.class);
	             Activity a = (Activity)c;
	              mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	              mIntent.putExtra("locationID", "0");
	              mIntent.putExtra("groupID", "1");
	              mIntent.putExtra("userID", userID);
	              a.startActivity(mIntent);
	         }
	      });
		/*친구 소식*/
		holder.friend_news.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mode = "friend";
				i = new Intent(c, MainActivity.class);
				Activity a = (Activity)c;
				i.putExtra("userID", userID);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				a.startActivityForResult(i,3);
				
			}
		});
		/*모든 소식*/
		holder.all_news.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mode = "all";
				i = new Intent(c, MainActivity.class);
				Activity a = (Activity)c;
				i.putExtra("userID", userID);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				a.startActivityForResult(i,3);
				
			}
		});
		/*그룹소식*/
		holder.group_news.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mode = "group";
				i = new Intent(c, MainActivity.class);
				Activity a = (Activity)c;
				i.putExtra("userID", userID);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				a.startActivityForResult(i,3);
			}
		});
		
		/*친구 관리*/
		holder.management_friends.setOnClickListener(new View.OnClickListener() {
	         
	         @Override
	         public void onClick(View v) {
	            // TODO Auto-generated method stub
	            int btnMyPost = 0;
	            Log.d("my_news", "my_news");
	            Intent mIntent = new Intent(c, ManageFriendActivity.class);
	             Activity a = (Activity)c;
	              mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	              mIntent.putExtra("userID", userID);
	              mIntent.putExtra("friendID", "0");
	              a.startActivity(mIntent);
	         }
	      });
		/*그룹 관리*/
		holder.management_group.setOnClickListener(new View.OnClickListener() {
	         
	         @Override
	         public void onClick(View v) {
	            // TODO Auto-generated method stub
	            int btnMyPost = 0;
	            Log.d("my_news", "my_news");
	            Intent mIntent = new Intent(c, ManageGroupActivity.class);
	             Activity a = (Activity)c;
	              mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	              mIntent.putExtra("userID", userID);
	              a.startActivity(mIntent);
	         }
	      });
		/*친구 추가*/
		holder.add_new_friends.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
				    	i = new Intent(c, AddFriendActivity.class);
				    	Activity a = (Activity)c;
				    	i.putExtra("userID", userID);
				    	a.startActivityForResult(i,3);
					}
				});
		/*계정 탈퇴*/
		holder.member_leave.setOnClickListener(
			new View.OnClickListener() {
								
								@Override
								public void onClick(View view) {
										new AlertDialog.Builder(c).setIcon(android.R.drawable.ic_dialog_alert).setTitle("계정탈퇴").setMessage("정말로 탈퇴하시겠습니까?")
										.setNeutralButton("No", null)
										.setPositiveButton("Yes", new DialogInterface.OnClickListener()
									   {
									     @Override
									     public void onClick( DialogInterface dialog, int which )
									     {
									    	 deleteUserInfoAsync myTask = new deleteUserInfoAsync();
											 myTask.execute();
									     }
									   }).show(); 
								}
							});
		/*0.5km*/
		holder.five_meter.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
				    	i = new Intent(c, MainActivity.class);
				    	Activity a = (Activity)c;
				    	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				    	i.putExtra("userID", userID);
				    	i.putExtra("select_radius", 0.5);
				    	a.startActivity(i);
				    	
					}
				});
		/*1km*/
		holder.one_kilometer.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						i = new Intent(c, MainActivity.class);
				    	Activity a = (Activity)c;
				    	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				    	i.putExtra("userID", userID);
				    	i.putExtra("select_radius", 1.0);
				    	a.startActivity(i);
					}
				});
		/*3km*/
		holder.three_kilometer.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						i = new Intent(c, MainActivity.class);
				    	Activity a = (Activity)c;
				    	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				    	i.putExtra("userID", userID);
				    	i.putExtra("select_radius", 3.0);
				    	a.startActivity(i);
					}
				});
		/*5km*/
		holder.five_kilometer.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						i = new Intent(c, MainActivity.class);
				    	Activity a = (Activity)c;
				    	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				    	i.putExtra("userID", userID);
				    	i.putExtra("select_radius", 5.0);
				    	a.startActivity(i);
					}
				});
		
		/*로그아웃*/
		holder.logout.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						
					
						new AlertDialog.Builder(activity).setIcon(android.R.drawable.ic_dialog_alert).setTitle("로그아웃").setMessage("로그아웃 하시겠습니까?").setNegativeButton( "아니오", null )
					      .setPositiveButton("예", new DialogInterface.OnClickListener()

					   {
					     @Override
					     public void onClick( DialogInterface dialog, int which )
					     {
					       activity.finish();
					     }
					   }).show(); 
					}
				});


		
		return convertView;
	}
	
	public String getterMode(){
		return mode;
	}
	/*계정 탈퇴시 서버와 영동하여 계정틀 없앤다*/
	protected String[] delete_user_info(Context context){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/delete_user.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	
       	if(conn != null){
       		conn.setConnectTimeout(15000);	
       		conn.setReadTimeout(15000);
       		conn.setDefaultUseCaches(false); 
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);  
           	conn.setRequestMethod("POST"); 
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
              
         	StringBuffer buffer = new StringBuffer();
         	
         	buffer.append("user_id").append("=").append(userID);
         	
            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();

           	pString =  builder.toString();
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	public class deleteUserInfoAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {

			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			delete_user_info(c);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			
			Intent mIntent = new Intent(c, LoginActivity.class);
			Activity a = (Activity)c;
	        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        mIntent.putExtra("userID", userID);
    		a.startActivity(mIntent);
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
	
}
